import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { 
  Send, 
  CheckCircle, 
  XCircle, 
  RotateCcw, 
  Clock,
  User,
  MessageSquare,
  AlertTriangle
} from 'lucide-react';
import { SchemeApproval, User as UserEntity } from "@/api/entities";

export default function ApprovalManager({ scheme, currentUser, onSchemeUpdate }) {
  const [approvalRecord, setApprovalRecord] = useState(null);
  const [comments, setComments] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [approvers, setApprovers] = useState([]);

  useEffect(() => {
    loadApprovalData();
  }, [scheme.id]);

  const loadApprovalData = async () => {
    try {
      const approvals = await SchemeApproval.filter({scheme_id: scheme.id}, '-created_date', 1);
      if (approvals.length > 0) {
        setApprovalRecord(approvals[0]);
      } else {
        setApprovalRecord(null);
      }

      const users = await UserEntity.list();
      const approverList = users.filter(user => 
        user.permissions && user.permissions.includes('scheme_approval')
      );
      setApprovers(approverList);
    } catch (error) {
      console.error('加载审批数据失败:', error);
    }
  };

  const handleActionWithStateUpdate = async (updateData) => {
    setIsSubmitting(true);
    try {
      await onSchemeUpdate(prev => ({ ...prev, ...updateData }));
    } finally {
      setIsSubmitting(false);
    }
  };


  const handleSubmitForApproval = async () => {
    setIsSubmitting(true);
    try {
      // Create approval record
      await SchemeApproval.create({
        scheme_id: scheme.id,
        submitter_id: currentUser?.id,
        current_approver_id: getNextApprover()?.id,
        approvalStatus: 'submitted',
        approval_level: 1,
        submit_time: new Date().toISOString(),
        comments: comments,
        approval_history: [{
          approver_id: currentUser?.id,
          approver_name: currentUser?.full_name || currentUser?.email,
          action: 'submit',
          comments: comments,
          timestamp: new Date().toISOString(),
          approval_level: 0
        }]
      });

      // Update scheme status
      onSchemeUpdate(prev => ({...prev, approvalStatus: 'review' }));

      alert('方案已提交审批');
      loadApprovalData();
    } catch (error) {
      console.error('提交审批失败:', error);
      alert('提交失败，请重试');
    }
    setIsSubmitting(false);
  };

  const handleApprovalAction = async (action) => {
    setIsSubmitting(true);
    try {
      const newHistory = [...(approvalRecord.approval_history || []), {
        approver_id: currentUser?.id,
        approver_name: currentUser?.full_name || currentUser?.email,
        action: action,
        comments: comments,
        timestamp: new Date().toISOString(),
        approval_level: approvalRecord.approval_level
      }];

      let newStatus = action === 'approve' ? 'approved' : 
                     action === 'reject' ? 'rejected' : 'returned';

      await SchemeApproval.update(approvalRecord.id, {
        approvalStatus: newStatus,
        comments: comments,
        approval_history: newHistory
      });

      let schemeNewStatus = newStatus === 'approved' ? 'approved' : 
                            newStatus === 'rejected' ? 'rejected' : 'draft';

      onSchemeUpdate(prev => ({...prev, approvalStatus: schemeNewStatus }));

      alert(`方案已${action === 'approve' ? '批准' : action === 'reject' ? '拒绝' : '退回'}`);
      setComments('');
      loadApprovalData();
    } catch (error) {
      console.error('审批操作失败:', error);
      alert('操作失败，请重试');
    }
    setIsSubmitting(false);
  };

  const getNextApprover = () => {
    return approvers.find(user => user.approval_level === 1);
  };

  const canSubmitApproval = () => {
    return !approvalRecord && currentUser && scheme.approvalStatus === 'draft';
  };

  const canApprove = () => {
    return approvalRecord && 
           currentUser && 
           approvalRecord.current_approver_id === currentUser.id &&
           (approvalRecord.approvalStatus === 'submitted' || approvalRecord.approvalStatus === 'in_review');
  };

  const getStatusConfig = (status) => {
    const configs = {
      draft: { label: '草稿', color: 'bg-gray-100 text-gray-700', icon: Clock },
      review: { label: '审核中', color: 'bg-orange-100 text-orange-700', icon: Clock },
      approved: { label: '已批准', color: 'bg-green-100 text-green-700', icon: CheckCircle },
      rejected: { label: '已拒绝', color: 'bg-red-100 text-red-700', icon: XCircle },
      returned: { label: '已退回', color: 'bg-yellow-100 text-yellow-700', icon: RotateCcw }
    };
    return configs[status] || configs.draft;
  };

  const statusConfig = getStatusConfig(scheme.approvalStatus);
  const StatusIcon = statusConfig.icon;

  return (
    <div className="space-y-6">
      {/* Current Status */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <StatusIcon className="w-5 h-5" />
            审批状态
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <Badge className={`${statusConfig.color} px-3 py-1 text-sm`}>
              {statusConfig.label}
            </Badge>
            {approvalRecord && (
              <div className="text-sm text-gray-600">
                提交时间: {new Date(approvalRecord.submit_time).toLocaleString('zh-CN')}
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Action Area */}
      <Card>
        <CardHeader>
          <CardTitle>操作</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Textarea
            value={comments}
            onChange={(e) => setComments(e.target.value)}
            placeholder={
              canSubmitApproval() ? "填写提交说明..." :
              canApprove() ? "填写审批意见..." : "当前状态无需填写意见"
            }
            rows={3}
            disabled={!canSubmitApproval() && !canApprove()}
          />
          
          <div className="flex gap-3">
            {canSubmitApproval() && (
              <Button 
                onClick={handleSubmitForApproval}
                disabled={isSubmitting || !comments.trim()}
                className="bg-blue-600 hover:bg-blue-700"
              >
                <Send className="w-4 h-4 mr-2" />
                {isSubmitting ? '提交中...' : '提交审批'}
              </Button>
            )}
            
            {canApprove() && (
              <>
                <Button 
                  onClick={() => handleApprovalAction('approve')}
                  disabled={isSubmitting}
                  className="bg-green-600 hover:bg-green-700"
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  批准
                </Button>
                <Button 
                  onClick={() => handleApprovalAction('reject')}
                  disabled={isSubmitting}
                  variant="destructive"
                >
                  <XCircle className="w-4 h-4 mr-2" />
                  拒绝
                </Button>
                <Button 
                  onClick={() => handleApprovalAction('return')}
                  disabled={isSubmitting}
                  variant="outline"
                >
                  <RotateCcw className="w-4 h-4 mr-2" />
                  退回修改
                </Button>
              </>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Approval History */}
      {approvalRecord && approvalRecord.approval_history && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MessageSquare className="w-5 h-5" />
              审批记录
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {approvalRecord.approval_history.map((record, index) => (
                <div key={index} className="border-l-4 border-blue-200 pl-4 py-2">
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <User className="w-4 h-4 text-gray-500" />
                      <span className="font-medium">{record.approver_name}</span>
                      <Badge variant="outline" className="text-xs">
                        {record.action === 'submit' ? '提交' :
                         record.action === 'approve' ? '批准' :
                         record.action === 'reject' ? '拒绝' : '退回'}
                      </Badge>
                    </div>
                    <span className="text-sm text-gray-500">
                      {new Date(record.timestamp).toLocaleString('zh-CN')}
                    </span>
                  </div>
                  {record.comments && (
                    <p className="text-gray-700 text-sm bg-gray-50 p-2 rounded">
                      {record.comments}
                    </p>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Prompts */}
      {!currentUser && (
        <Card className="border-yellow-200 bg-yellow-50">
          <CardContent className="pt-6">
            <div className="flex items-center gap-2 text-yellow-700">
              <AlertTriangle className="w-5 h-5" />
              <span>请先登录以使用审批功能</span>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}